#import "SEGProfileManager.h"

#define kNSUserDefaultsUserId @"seg_USERID"

#if __has_include(<Commom/SEGModel.h>)
#import <Commom/SEGModel.h>
#else
#import "SEGModel.h"
#endif

#if __has_include(<Commom/SEGHTTPBusinessManager.h>)
#import <Commom/SEGHTTPBusinessManager.h>
#else
#import "SEGHTTPBusinessManager.h"
#endif

#if __has_include(<Commom/YYBaseHeader.h>)
#import <Commom/YYBaseHeader.h>
#else
#import "YYBaseHeader.h"
#endif

#if __has_include(<SEGPlatform/SEGPlatformManager.h>)
#import <SEGPlatform/SEGPlatformManager.h>
#else
#import "SEGPlatformManager.h"
#endif

#if __has_include(<SEGPlatform/SEGBussinessConstHeader.h>)
#import <SEGPlatform/SEGBussinessConstHeader.h>
#else
#import "SEGBussinessConstHeader.h"
#endif

#import "SEGQueryauthinfoManager.h"
//#import "SEGQueryauthinfoModel.h"
#import "SEGLoginV2Manager.h"

static id _profileManager;
static dispatch_once_t onceToken;

@implementation SEGProfileManager
#pragma mark - SINGLE----BEGIN----
+(instancetype)sharedManager{
    dispatch_once(&onceToken, ^{
        _profileManager = [[self alloc] init];
    });
    return _profileManager;
}

+(void)destroyResource{
    onceToken = 0;
    _profileManager = nil;
}

#pragma mark - SINGLE----END----

#pragma mark - HTTP----BEGIN----
-(void)requestProfilecompleted:(void(^)(BOOL isSuccessed,id result,NSString* codeType,NSString* errorMessage))completed{
    
    NSString *urlString = [SEGServerManager serverUrlJoint:kClientRootURL,@"/uhomecp-sso/v3/userApp/profile",nil];
    [SEGHTTPBusinessManager seg_requestWithMethod:GET URLString:urlString parameters:nil completed:^(BOOL isSuccessed, id result, NSString *codeType, NSError *error) {
        if (!isSuccessed || result == nil) {
            completed(NO,nil,codeType,error.localizedDescription);
            return;
        }
        
        if (![result isKindOfClass:[NSDictionary class]]) {
            completed(NO,nil,codeType,error.localizedDescription);
            return;
        }
        
        self.profile = [SEGProfileModel yy_modelWithJSON:result[@"data"]];
        [[NSUserDefaults standardUserDefaults] setObject:self.profile.userId forKey:kNSUserDefaultsUserId];
        [[NSUserDefaults standardUserDefaults] synchronize];
        [SEGProfileManager seg_SaveSystemAccountWithUserID:self.profile];
        completed(YES,result,codeType,error.localizedDescription);
        return;
    }];
}

/**
 * 保存本地缓存的用户信息
 * @author Sam
 * @param userAccount  服务器下发的缓存信息
 * @return YES：本地缓存成功，NO：本地缓存失败
 */
+ (BOOL)seg_SaveSystemAccountWithUserID:(SEGProfileModel*)userAccount
{
    NSString* path = [self path_UserInforWithUserID:userAccount.userId];
    return [NSKeyedArchiver archiveRootObject:userAccount toFile:path];
}

/**
 * 获取本地缓存的用户信息
 * @author Sam
 * @return 本地缓存的用户信息模型
 */
+ (SEGProfileModel *)seg_GetSystemAccount;
{
    NSString * userID = [self segUserIdFromLocal];
    NSString* path = [self path_UserInforWithUserID:userID];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
        return [[SEGProfileModel alloc]init];
    }
    // TODO: 组件化，在覆盖旧APP的时候会闪退，第一次覆盖，需要进行定位！
    SEGProfileModel* account = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    return account;
}

/**
 * 获取本地的用户ID
 * @author Sam
 */
+(NSString*)segUserIdFromLocal{
    return ValueToString([[NSUserDefaults standardUserDefaults] valueForKey:kNSUserDefaultsUserId]);
}

/**
 * 用户信息本地缓存路径
 * @author Sam
 */
+ (NSString*)path_UserInforWithUserID:(NSString*)userID
{
    return [NSString stringWithFormat:@"%@/ProfileAccount_%@.data", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject, userID];
}
#pragma mark - HTTP----END----

+ (SEGEnumOpendoorShowType)openDoorType
{

    SEGProfileModel* curAccount = [SEGProfileManager sharedManager].profile;
    BOOL isAuthed; // 用户是否已认证
    isAuthed = ([curAccount.type intValue] != kUserTypeZiLBuQ) ? YES : NO;
    BOOL isOpened = ([curAccount.sign integerValue] == 1) ? YES : NO; //小区是否开通门禁
    SEGEnumOpendoorShowType type = SEGEnumOpendoorShowType_NoCooperation;
    // 先判断是否开通门禁服务
    if (!isOpened) {
        type = SEGEnumOpendoorShowType_NoCooperation;
    }else if(!isAuthed) {
        type = SEGEnumOpendoorShowType_NoCertification;
    }
    else{
        type = SEGEnumOpendoorShowType_List;
    }
    return type;
}

#pragma mark - 拉黑功能
/// 拉黑用户
/// @param userId 被拉黑用户的Id
+ (void)seg_setBlacklistForUserId:(NSString *)userId {
    if (![kAccountUserID isEqualToString:kAccountBlacklistUserId]) return;
    NSSet *set = [SEGProfileManager seg_getBlacklist];
    NSMutableSet *mSet = [NSMutableSet setWithSet:set];
    [mSet addObject:userId];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@_blacklist.data", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject, kAccountBlacklistUserId];
    [NSKeyedArchiver archiveRootObject:mSet toFile:filePath];
}
/// 获取userId = @“1245” 用户的拉黑名单
+ (NSSet *)seg_getBlacklist {
    if (![kAccountUserID isEqualToString:kAccountBlacklistUserId]) return [NSSet new];
    NSString *filePath = [NSString stringWithFormat:@"%@/%@_blacklist.data", NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject, kAccountBlacklistUserId];
    return [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}

#pragma mark - GETTER----BEGIN----
- (SEGProfileModel *)profile {
    if (!_profile) {
        _profile = [[SEGProfileModel alloc] init];
        _profile = [SEGProfileManager seg_GetSystemAccount];
    }
    return _profile;
}

#pragma mark - GETTER----END----

@end
